package GlavFinans::Module::Core::Controller::Auth;

use utf8;
use Data::Dumper;
use Mojo::Base 'Mojolicious::Controller';
use CGI::Session;

sub logout {
	my $self = shift;
	
	my $session = $self->stash('session');
	
	$session->expire(1);
	$session->delete();
	$session->flush();
	
	$self->redirect_to('/');
}

sub lostpw {
	my $self = shift;
	
	my $note;
	if ( $self->req->method eq 'POST' ) {
		my $email = $self->req->param('email');
		my $user = $self->app->db->resultset('User')->search({ email => $email })->single;
		
		if($user) {
			my $host = $self->req->headers->host;
			my $body = $self->render_mail( template => 'auth/lostpw', user => $user, host => $host );
			$self->mail( 
				to => $email,
				subject => $self->stash('subject'),
				data => $body
			);
		}
	}
	
	$self->render('core/auth/lostpw', note => $note);
}

sub checkSession {
	my $self = shift;
	my $config = $self->stash->{config};
	my $memcached = $self->stash->{memcached};

	my $sid = $self->cookie($config->{session}->{name});

	my $session;
	unless ( defined $sid) {
		$session = CGI::Session->new( 'driver:memcached', undef, { Memcached => $memcached } );
	} else {
		$session = CGI::Session->new( 'driver:memcached', $sid, { Memcached => $memcached } );
	}
	
	unless ($session) {
		warn CGI::Session->errstr();
	}
	
	my $user;
	my $guid = $session->param('user:guid');
	unless ($guid) {
		$user = $self->app->db->resultset('User')->search({ role => 'anonymous' })->single;
	} else {
		$user = $self->app->db->resultset('User')->search({ guid => $guid })->single;
	}
	
	my $expire = $session->atime() + $config->{session}->{expire};
	$session->expire( $expire );
		
	$self->res->cookies({ 
		name    => $config->{session}->{name}, 
		value   => $session->id, 
		expires => $expire 
	});
	
	$self->stash( session => $session, 
					user => $user );
	
	return 1;
}

sub login {
	my $self = shift;
	
	my $session = $self->stash->{session};
	
	if ( $self->req->method eq 'POST' ) {
		my $email = $self->req->param('login');
		my $pass = $self->req->param('pass');
		my $user = $self->app->db->resultset('User')->search({ email => $email, password => $pass })->single;
		if ( $user ) {
			$session->param( 'user:guid', $user->guid );
			$self->redirect_to($session->param('login-from'));
		}
	} else { 
		$self->render(template => 'core/auth/login');
	}
}

sub checkAuth {
	my $self = shift;
	
	my $session = $self->stash->{session};
	if ( $session->param('user:guid') ) {
		return 1;
	} else {
		$session->param('login-from', $self->req->url);
		$self->redirect_to('/login');
		return 0;	
	};
}

1;
